# Author: zhuxuanlin
# Email: xuanlinzhu@qq.com
# Date: 2025-6-29

# Description: This file is used to create a quick template project for CMake.

import os

# 脚本版本 
ck_pylib_version = "2.0.0"
def parse_config_file_cmake(config_file):
    config_vars = {}
    with open(config_file, 'r') as f:
        for line in f:
            # Skip comments and empty lines
            if line.startswith('#') or line.strip() == '':
                continue
            # Parse configuration line
            key, value = line.strip().split('=', 1)
            # Remove 'CONFIG_' prefix from the key name
            key = key[7:] if key.startswith('CONFIG_') else key
            # Handle quotes in the value
            if value.startswith('"') and value.endswith('"'):
                value = value[1:-1]
            # Add to dictionary
            config_vars[key] = value
    return config_vars


def write_cmake_file(config_vars, cmake_file):
    with open(cmake_file, 'w') as f:
        f.write('# Automatically generated by ck_pylib\n# author:zxl ver:'+ck_pylib_version+'\n')
        for key, value in config_vars.items():
            f.write('set({} "{}")\n'.format(key, value))


def convert_config_to_cmake(config_file, cmake_file):
    config_vars = parse_config_file_cmake(config_file)
    write_cmake_file(config_vars, cmake_file)


def parse_config_file_header(config_file):
    config_vars = []
    with open(config_file, 'r') as f:
        for line in f:
            # Skip comments and empty lines
            if line.startswith('#') or line.strip() == '':
                continue
            # Parse configuration line
            key, value = line.strip().split('=', 1)
            # If the value is 'y', replace it with a space
            value = value.strip()
            if value == 'y':
                value = '1'
            # Remove 'CONFIG_' prefix from the key name
            key = key[7:] if key.startswith('CONFIG_') else key
            # Add to list
            config_vars.append((key, value))
    return config_vars


def write_config_header(config_vars, header_file):
    import re

    # 这三个需要保留/添加的宏
    fixed_macros = {
        'CK_SOFTWARE_VERSION': '"0.0.1"',
        'CK_SOFTWARE_BUILD_TIME': '"1970-01-01 00:00:00"',
        'CK_SOFTWARE_COMMIT_HASH': '"0000000"'
    }

    # 尝试读取旧文件中这三个宏的值
    existing_macros = {}
    if os.path.exists(header_file):
        with open(header_file, 'r') as f:
            for line in f:
                for macro in fixed_macros:
                    m = re.match(r'#define\s+' + macro + r'\s+"(.+)"', line)
                    if m:
                        existing_macros[macro] = f'"{m.group(1)}"'

    # 更新 fixed_macros，优先使用旧值
    for macro in fixed_macros:
        if macro in existing_macros:
            fixed_macros[macro] = existing_macros[macro]

    # 把 config_vars（来自 .config）转为 dict，避免重复键
    config_dict = {k: v for k, v in config_vars}

    # 将 fixed_macros 注入 config_dict，确保被写入
    config_dict.update(fixed_macros)

    # 写入文件
    with open(header_file, 'w') as f:
        f.write('/* Automatically generated by ck_pylib */\n')
        f.write('/* author:zxl ver:' + ck_pylib_version + ' */\n')
        f.write('#ifndef __CK_CONFIG_H__\n#define __CK_CONFIG_H__\n\n')

        for key, value in sorted(config_dict.items()):
            f.write(f'#define {key} {value}\n')

        f.write('\n#endif // __CK_CONFIG_H__\n')




def convert_config_to_header(config_file, header_file):
    config_vars = parse_config_file_header(config_file)
    write_config_header(config_vars, header_file)


config_file = '.config'       # Path to your .config file
cmake_file = 'ck_config.cmake'  # Path to the generated config.cmake file
header_file = 'ck_config.h'     # Path to the generated lr_config.h file

# Convert .config file to config.cmake file
convert_config_to_cmake(config_file, cmake_file)

# Convert .config file to lr_config.h file
convert_config_to_header(config_file, header_file)